package top.rainf.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.rainf.mapper.UserBaseInfoMapper;
import top.rainf.service.ILoginService;
import top.rainf.util.MD5Util;
import top.rainf.util.StringUtil;
import top.rainf.domain.vo.UserBaseInfo;

import java.sql.Timestamp;

/**
 * @author 星环
 * @date 2023/5/8 14:54:42
 * @description
 */
@Service
public class LoginService implements ILoginService {
    @Autowired
    UserBaseInfoMapper userBaseInfoMapper;
    @Override
    public UserBaseInfo login(String username, String pwd, String code, String realCode) {
        boolean codeCorrect = verifyCaptcha(code,realCode);
        if(!codeCorrect){
            return null;
        }
        UserBaseInfo userBaseInfo = userBaseInfoMapper.selectUserBaseInfoByUsernameAndPassword(username, MD5Util.encode(pwd));
        if(userBaseInfo != null){
            Timestamp lastLoginTime = new Timestamp(System.currentTimeMillis());
            userBaseInfoMapper.updateLastLoginTimeById(userBaseInfo.getId(), lastLoginTime);
            userBaseInfo.setLastLoginTime(lastLoginTime);
        }
        return userBaseInfo;
    }

    /**
     * 生成重置密码的凭证，用于重置密码验证，用户访问网站时，如果有指定的凭证，就可以修改对应用户的密码
     * 用户使用凭证后需要把对应的凭证删除
     * @param username 用户名
     * @param email 邮箱
     * @param realCode 验证码
     * @return 根据以上三者生成的凭证，暂定把三者拼接后md5加密一次
     */
    @Override
    public String generateResetPasswordToken(String username, String email, String realCode) {
        StringBuilder sb = new StringBuilder();
        sb.append(username).append(email).append(realCode);
        String s = sb.toString();
        String encode = MD5Util.encode(s);
        return encode;
    }

    @Override
    public boolean verifyCaptcha(String code, String realCode) {
        if(StringUtil.isNullOrEmpty(code) || StringUtil.isNullOrEmpty(realCode)){
            return false;
        }
        return realCode.equalsIgnoreCase(code);
    }
}
